package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import cn.edu.sdjzu.xg.bysj.service.ApplicationForSupervisorService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import test.BysjException;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@WebServlet("/AFS.ctl")
public class ApplicationForSupervisorController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //将JSON字串解析为对象
        JSONArray ApplicationForSupervisorList_jsonArray =
               req_jsonObj.getJSONArray("ApplicationForSupervisorList");
        //前端传来的ApplicationForSupervisorList
        List<ApplicationForSupervisor> applicationForSupervisorList =
                       ApplicationForSupervisorList_jsonArray.toJavaList(ApplicationForSupervisor.class);

        List<ApplicationForSupervisorEntry> applicationForSupervisorEntries
                =new ArrayList<ApplicationForSupervisorEntry>();
        for(ApplicationForSupervisor c: applicationForSupervisorList){
            for(ApplicationForSupervisorEntry e:c.getApplicationForSupervisorEntries()){
                e.setApplicationForSupervisor(c);
                applicationForSupervisorEntries.add(e);
            }
            c.setApplicationForSupervisorEntries(applicationForSupervisorEntries);
        }

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加对象
        try {
            ApplicationForSupervisorService.getInstance().add(applicationForSupervisorList);
            message.put("message", "增加成功");
            log.debug("增加成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
        }
        catch (BysjException e){
            message.put("message", e.getMessage());
            log.debug(e.getMessage());
        }
        catch(Exception e){
            message.put("message", "网络异常");
            e.printStackTrace();
        }
        //响应message到前端
        response.getWriter().println(message);
    }
}
